package io.aicn.lowcode.controller.dbmanager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.aicn.lowcode.entity.dbmanager.DataDictionary;
import io.aicn.lowcode.service.dbmanager.IDataDictionaryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典Controller
 * 
 * @author lowcode-generator
 * @since 2025-01-25
 */
@Slf4j
@RestController
@RequestMapping("/api/dbmanager/dictionary")
@Tag(name = "数据字典管理", description = "数据字典的增删改查")
public class DataDictionaryController {

    @Autowired
    private IDataDictionaryService dataDictionaryService;

    @Operation(summary = "分页查询数据字典列表")
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "字典类型") @RequestParam(required = false) String dictType,
            @Parameter(description = "字典标签") @RequestParam(required = false) String dictLabel,
            @Parameter(description = "是否启用") @RequestParam(required = false) Boolean isEnabled) {
        
        Page<DataDictionary> page = new Page<>(current, size);
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        
        if (dictType != null && !dictType.trim().isEmpty()) {
            queryWrapper.eq("dict_type", dictType.trim());
        }
        if (dictLabel != null && !dictLabel.trim().isEmpty()) {
            queryWrapper.like("dict_label", dictLabel.trim());
        }
        if (isEnabled != null) {
            queryWrapper.eq("status", isEnabled ? "0" : "1");
        }
        
        queryWrapper.orderByAsc("dict_type").orderByAsc("sort_order");
        
        Page<DataDictionary> result = dataDictionaryService.page(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());
        response.put("current", result.getCurrent());
        response.put("size", result.getSize());
        response.put("pages", result.getPages());
        
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "根据字典类型查询字典列表")
    @GetMapping("/list/{dictType}")
    public ResponseEntity<List<DataDictionary>> listByType(
            @Parameter(description = "字典类型") @PathVariable String dictType) {
        
        List<DataDictionary> list = dataDictionaryService.listByType(dictType);
        return ResponseEntity.ok(list);
    }

    @Operation(summary = "查询所有字典类型")
    @GetMapping("/types")
    public ResponseEntity<List<String>> getDictTypes() {
        List<String> types = dataDictionaryService.getDictTypes();
        return ResponseEntity.ok(types);
    }

    @Operation(summary = "根据ID查询数据字典详情")
    @GetMapping("/{id}")
    public ResponseEntity<DataDictionary> getById(@Parameter(description = "字典ID") @PathVariable Long id) {
        DataDictionary dataDictionary = dataDictionaryService.getById(id);
        if (dataDictionary == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(dataDictionary);
    }

    @Operation(summary = "根据类型和编码查询字典项")
    @GetMapping("/item")
    public ResponseEntity<DataDictionary> getByTypeAndCode(
            @Parameter(description = "字典类型") @RequestParam String dictType,
            @Parameter(description = "字典编码") @RequestParam String dictCode) {
        
        DataDictionary dataDictionary = dataDictionaryService.getByTypeAndCode(dictType, dictCode);
        if (dataDictionary == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(dataDictionary);
    }

    @Operation(summary = "创建数据字典")
    @PostMapping
    public ResponseEntity<Map<String, Object>> create(@RequestBody DataDictionary dataDictionary) {
        try {
            // 检查同类型下编码是否重复
            DataDictionary existing = dataDictionaryService.getByTypeAndCode(
                dataDictionary.getDictType(), dataDictionary.getDictCode());
            if (existing != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "该字典类型下编码已存在: " + dataDictionary.getDictCode());
                return ResponseEntity.badRequest().body(response);
            }

            boolean success = dataDictionaryService.save(dataDictionary);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "创建成功" : "创建失败");
            response.put("data", dataDictionary);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建数据字典失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "更新数据字典")
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "字典ID") @PathVariable Long id,
            @RequestBody DataDictionary dataDictionary) {
        try {
            DataDictionary existing = dataDictionaryService.getById(id);
            if (existing == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据字典不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查同类型下编码是否重复（排除自己）
            DataDictionary duplicate = dataDictionaryService.getByTypeAndCode(
                dataDictionary.getDictType(), dataDictionary.getDictCode());
            if (duplicate != null && !duplicate.getId().equals(id)) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "该字典类型下编码已存在: " + dataDictionary.getDictCode());
                return ResponseEntity.badRequest().body(response);
            }

            dataDictionary.setId(id);
            boolean success = dataDictionaryService.updateById(dataDictionary);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "更新成功" : "更新失败");
            response.put("data", dataDictionary);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新数据字典失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "删除数据字典")
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@Parameter(description = "字典ID") @PathVariable Long id) {
        try {
            boolean success = dataDictionaryService.removeById(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "删除成功" : "删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除数据字典失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "批量删除数据字典")
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            boolean success = dataDictionaryService.removeByIds(ids);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "批量删除成功" : "批量删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("批量删除数据字典失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "更新字典启用状态")
    @PutMapping("/{id}/enabled")
    public ResponseEntity<Map<String, Object>> updateEnabled(
            @Parameter(description = "字典ID") @PathVariable Long id,
            @Parameter(description = "是否启用") @RequestParam Boolean isEnabled) {
        try {
            DataDictionary dataDictionary = dataDictionaryService.getById(id);
            if (dataDictionary == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据字典不存在");
                return ResponseEntity.notFound().build();
            }

            dataDictionary.setStatus(isEnabled ? "0" : "1");
            boolean success = dataDictionaryService.updateById(dataDictionary);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "状态更新成功" : "状态更新失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新字典状态失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "状态更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}